<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title></title>
	<style type="text/css">
		#uList {list-style: none;}
		#uList li {float: left; width: 100px; height: 100px; margin: 10px; border: 1px solid #ccc; position: relative;}
		#uList li img {width: 100%; height: 100%; }
		.btn_del {text-decoration: none; position: absolute; right: 0px; top: 0px; }
		#box {
			width: 500px;
			height: 300px;
			line-height: 300px;
			/* display: none; */
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			text-align: center;
			border: 1px solid black;
		}
	</style>
</head>
<body>
	<meter value="" min="0" max="100" style="width: 100%;" id="m1"></meter>
	<ul id="uList"></ul>
	<button id="btn_upload">上传</button>
	<div id="box">请把文件拖拽到这里</div>
</body>
<script src="./xhr3.0.js"></script>
<script>
	window.onload=function() {
		let box=document.querySelector('#box');
		let uList=document.querySelector('#uList');
		let btn_upload=document.querySelector('#btn_upload');
		let timer=null;
		
		document.addEventListener('dragover', function(ev) { // ==> 一直在执行
			if(timer) {clearTimeout(timer);}; //每隔300ms检测一下是否有文件拖拽进来
			box.style.display='block';
			timer=setTimeout(function() {
				box.style.display='none';
			}, 300);
			ev.preventDefault();
		});
		
		box.addEventListener('dragenter', function() {
			box.innerHTML='请松手';
		});
		box.addEventListener('dragleave', function() {
			box.innerHTML='请把文件拖拽到这里';
		})
		box.addEventListener('drop', function(ev) {
			// ev.dataTransfer.files
			Array.from(ev.dataTransfer.files).forEach(file=>{
				// if(!file.type.startsWith('image/')) {return;}
				let reader=new FileReader();
				reader.onload=function() {
					// reader.result
					let li=document.createElement('li');
					li.file=file;
					li.innerHTML=`<img src="${reader.result}" alt=""><a href="javascript:;" class="btn_del">删除</a>`
					uList.appendChild(li);
				};
				reader.readAsDataURL(file);
			})
			ev.preventDefault();
		});
		
		// 删除元素
		uList.onclick=function(ev) {
			uList.removeChild(ev.target.parentElement);
		}
		btn_upload.addEventListener('click', async function() {
			let formdata=new FormData();
			Array.from(uList.children).forEach((li, index)=>{
				formdata.append(`file${index}`, li.file);
			});
			try {
				let res=await ajax({
					url: 'http://localhost:3000',
					method: 'post',
					body: formdata
				});
				console.log(res);
			} catch(err) {
				console.log(err);
			}
		});
	};
</script>
</html>